package com.bfly.mall.product.api;

import com.alibaba.fastjson.JSONObject;
import com.bfly.common.ResponseUtil;
import com.bfly.common.util.TenCentMapUtil;
import com.bfly.core.base.controller.BaseController;
import com.bfly.core.base.entity.ResponseData;
import com.bfly.core.enums.SysError;
import com.bfly.core.exception.ServiceResponseException;
import com.bfly.mall.product.entity.FreightFreeConditions;
import com.bfly.mall.product.entity.FreightTemplate;
import com.bfly.mall.product.entity.FreightTemplatePricing;
import com.bfly.mall.product.enums.PricingMethodEnum;
import com.bfly.mall.product.service.IFreightTemplateService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 运费模板API
 *
 * @author 长沙商脉科技有限公司
 * @date 2020/9/21 19:42
 */
@RestController
@RequestMapping(value = "/api/freight")
public class FreightTemplateApiController extends BaseController {

    @Autowired
    private IFreightTemplateService freightTemplateService;

    /**
     * 产品运费标题
     * 坐标和城市同时存在的时候以坐标为主
     *
     * @author 长沙商脉科技有限公司
     * @date 2020/11/9 19:56
     */
    @GetMapping(value = "/title")
    public void getFreightTitle(HttpServletResponse response, HttpServletRequest request,
                                @RequestParam("productId") int productId,
                                @RequestParam(value = "latitude", defaultValue = "") String latitude,
                                @RequestParam(value = "longitude", defaultValue = "") String longitude,
                                @RequestParam(value = "city", defaultValue = "") String city,
                                @RequestParam(value = "province", defaultValue = "") String province) throws Exception {
        FreightTemplate freight = freightTemplateService.getFreight(productId);
        if (freight == null) {
            throw new ServiceResponseException(SysError.PARAM_ERROR, "不存在的运费模板信息!");
        }
        if (StringUtils.isNotBlank(latitude) && StringUtils.isNotBlank(longitude)) {
            JSONObject json = TenCentMapUtil.getAddress(latitude, longitude);
            city = json.getString("city");
        }
        JSONObject json = new JSONObject();
        json.put("isFree", false);
        json.put("city", city);
        if (freight.isFreeShipping()) {
            json.put("isFree", true);    // 全国包邮
        } else {
            List<FreightTemplatePricing> pricings = freight.getPricings();
            String shortCity = city;
            int index = city.lastIndexOf("市");
            if (index > 0) {
                shortCity = city.substring(0, index);
            }
            boolean exist = false;    // 是否存在指定地区运价
            FreightTemplatePricing selectPricing = null;
            for (FreightTemplatePricing pricing : pricings) {
                if (pricing.getCityNames().contains(city) || pricing.getCityNames().contains(shortCity) || (StringUtils.isNotBlank(province) && pricing.getCityNames().contains(province))) {
                    exist = true;
                    selectPricing = pricing;
                    break;
                }
            }
            if (!exist) {
                // 使用全国默认运费
                for (FreightTemplatePricing pricing : pricings) {
                    if (pricing.isDefaults()) {
                        selectPricing = pricing;
                        break;
                    }
                }
            }
            PricingMethodEnum methodEnum = PricingMethodEnum.getPricingMethod(freight.getPricingMethod());
            switch (methodEnum) {
                case PIECE:
                    json.put("firstCount", selectPricing.getFirstPiece() + "件");
                    json.put("nextCount", selectPricing.getNextPiece() + "件");
                    break;
                case VOLUME:
                    json.put("firstCount", selectPricing.getFirstVolume() + "m³");
                    json.put("nextCount", selectPricing.getNextVolume() + "m³");
                    break;
                case WEIGHT:
                    json.put("firstCount", selectPricing.getFirstWeight() + "KG");
                    json.put("nextCount", selectPricing.getNextWeight() + "KG");
                    break;
            }
            json.put("firstPrice", selectPricing.getFirstPrice() + "元");
            json.put("nextPrice", selectPricing.getNextPrice() + "元");

            json.put("isCondition", false);
            if (freight.isFreeConditions()) {
                // 指定了包邮条件
                List<FreightFreeConditions> conditions = freight.getConditions();
                for (FreightFreeConditions condition : conditions) {
                    if (condition.getCityNames().contains(city) || condition.getCityNames().contains(shortCity) || (StringUtils.isNotBlank(province) && condition.getCityNames().contains(province))) {
                        json.put("pricingMethodName", methodEnum.getName());
                        if (freight.getPricingMethod() == condition.getPricingMethod()) {
                            json.put("isCondition", true);
                            switch (methodEnum) {
                                case PIECE:
                                    json.put("condition", condition.getPieces() + "件");
                                    break;
                                case MONEY:
                                    json.put("condition", condition.getPrices() + "元");
                                    break;
                                case VOLUME:
                                    json.put("condition", condition.getVolumes() + "m³");
                                    break;
                                case WEIGHT:
                                    json.put("condition", condition.getWeights() + "KG");
                                    break;
                                case PIECE_MONEY:
                                    json.put("condition", condition.getPieces() + "件 或满" + condition.getPrices() + "元");
                                    break;
                            }
                            break;
                        }
                    }
                }
            }
        }
        ResponseUtil.writeJson(response, ResponseData.getSuccess(json));
    }

}